package com.wang.mandkey.tool;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.swing.JTextArea;

import com.wang.mandkey.net.INetCallBack;

public class ScriptRunnerThread implements Runnable {

	private InputStream dataInputStream;
	private OutputStream dataOutputStream;
	private Socket socketClient;
	private boolean booleanAlive = true;
	private Thread thread;
	private INetCallBack iNetCallBack;
	private JTextArea jta;

	public ScriptRunnerThread(Socket socketClient, INetCallBack iNetCallBack,
			JTextArea jta) {
		try {
			this.socketClient = socketClient;
			this.socketClient.setReceiveBufferSize(4);
			// this.socketClient.setKeepAlive(true);
			dataInputStream = this.socketClient.getInputStream();
			dataOutputStream = this.socketClient.getOutputStream();
			String scren = "screen:" + Tool.getScreenDimen().width + ":"+ Tool.getScreenDimen().height;
			this.dataOutputStream.write(scren.getBytes());
			this.iNetCallBack = iNetCallBack;
			this.jta = jta;
		} catch (IOException e) {
			e.printStackTrace();
			iNetCallBack.onNetInterupt();
			closeServerSocket();
		}

	}

	@Override
	public void run() {
		System.out.println("scripRunnerThread is start...");
		this.jta.append("命令解析服务开启...\n");
		while (booleanAlive) {
			try {
				String utfCode = "";
				byte[] codeBuf = new byte[8192];
				int ret=dataInputStream.read(codeBuf);
				if(0==ret){
					continue;
				}
				utfCode = new String(codeBuf, 0, ret);
				System.out.println("utf code:" + utfCode);
				jta.append("utf code:" + utfCode + "\n");
				String t = jta.getText();
				if(t.length()>1000){
					jta.setText(null);
				}
				if(utfCode.contains("|")){
					String[] comds = utfCode.split("\\|");
					for (int i = 0; i < comds.length; i++) {
						String comd = comds[i];
						if (comd.startsWith("#")) {// 命令以#开头
							CommandTool.exeCcommand(comd.substring(1));
						} else if (utfCode.startsWith("$")) {
							CommandTool.execDos(comd.substring(1));
						}
						ScriptRunner.execAction(comd);
					}
				}else{
					String comd = utfCode;
					if (comd.startsWith("#")) {// 命令以#开头
						CommandTool.exeCcommand(comd.substring(1));
					} else if (utfCode.startsWith("$")) {
						CommandTool.execDos(comd.substring(1));
					}
					ScriptRunner.execAction(comd);
				}
				
				
			} catch (IOException e) {
				this.iNetCallBack.onNetInterupt();
				e.printStackTrace();
				killSlef();
				break;
			}

		}

	}

	public void startMe() {
		thread = new Thread(this);
		thread.start();
	}

	/**
	 * 线程停止信号
	 */
	public void killSlef() {
		booleanAlive = false;
		closeServerSocket();
	}

	public void closeServerSocket() {
		if (null != socketClient && socketClient.isClosed() == false) {
			try {
				socketClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		closeServerSocket();
	}

}
